<?php
class GalleriesController extends AppController {
	var $name = 'Galleries';
    var $components = array('Email');

    public function axUpload ($no='') {
        Configure::write('debug', 0);

        App::import('Vendor', 'Image', array('file'=>'image.class.php'));

        $json = $this->params['form'];
        $name = basename($_FILES['uploadImage']['tmp_name']);

        list($width, $height, $mime,) = @getimagesize($_FILES['Filedata']['tmp_name']);

        $img = new Upload($_FILES['uploadImage']);

        $img->file_max_size      = 4096000;
        $img->allowed            = array('image/jpeg', 'image/pjpeg', 'image/gif', 'image/png');
        $img->file_new_name_body = 's_'.$name;
        $img->image_min_width    = 64;
        $img->image_min_height   = 64;
        $img->image_x            = 194;
        $img->image_y            = 155;
        $img->image_ratio_crop   = true;
        $img->image_resize       = true;
        $img->Process(IMAGES.'tmp'.DS);

        if ($img->processed) {
            $thumbnail = $img->file_dst_name;

            $img->file_new_name_body = $name;
            $img->image_x            = 570;
            $img->image_y            = 380;
            $img->image_ratio        = true;
            $img->image_resize       = true;
            $img->Process(IMAGES.'tmp'.DS);

            if ($img->processed) {
                $filename = $img->file_dst_name;
            } else {
                $this->response(array(
                    'status' => '0',
                    'error'  => __($img->error, true)
                ));
                return;
            }
        } else {
            $json = array(
                'status'  => -1,
                'message' => __($img->error, true)
            );
        }
        $img->Clean();

        $this->set('json', array(
            'status'    => 1,
            'filename'  => $filename,
            'thumbnail' => $thumbnail
        ));
        $this->render(false, 'json');
        sleep(1);
    } // axUpload

    public function upload ($id='') {
        if ($this->RequestHandler->isAjax()) {
            $this->data['Gallery'] = $this->params['form'];
            $valid = true;

            if (!$this->data) {
                $json = array(
                    'status' => false,
                    'mesg'   => __('no data posted', true)
                );
                $this->response($json);
                return;
            }

            foreach ($this->data['Gallery'] as $fieldname=>$value) {
                if (empty($value) && $value != '0' && $fieldname != 'id') {
                    $this->data['Gallery'][$fieldname] = null;
                }
            }

            $this->Gallery->set($this->data);

            if ($this->Gallery->validates() && $valid) { // data validated!
                if ($this->Gallery->save($this->data)) {
                    $mesg = empty($this->params['form']['id']) ? __('Your gallery has been submited successfully!',true) : __('Gallery has been updated successfully!',true);
                    $json = array(
                        'status' => true,
                        'id'     => $this->Gallery->id,
                        'mesg'   => $mesg
                    );

                    $img = $this->data['Gallery']['filename'];
                    $thm = 's_'.$img;

                    if (file_exists(IMAGES.'tmp'.DS.$img)) {
                        @rename(IMAGES.'tmp'.DS.$img, IMAGES.'gallery'.DS.$img);
                    }
                    if (file_exists(IMAGES.'tmp'.DS.$thm)) {
                        @rename(IMAGES.'tmp'.DS.$thm, IMAGES.'gallery'.DS.$thm);
                    }

                    $this->_sendMail($this->data['Gallery'], $this->Gallery->id);
                } else {
                    $mesg = empty($this->params['form']['id']) ? __('Fail submmit your gallery at this time, please try again.',true) : __('Fail update Gallery to database at this time, please try again.',true);
                    $err  = ($this->error) ? $this->error : $mesg;
                    $json = array(
                        'status' => false,
                        'mesg'   => $err
                    );
                }
            } else { // invalid data found
                $json = array(
                    'status' => false,
                    'mesg'   => __('Please enter the requested details in the fields pointed out below and try again!', true)
                );
                foreach ($this->Gallery->invalidFields() as $k=>$v) {
                    $json['error'][] = array('id'=>$k, 'field'=>$k, 'code'=>$v);
                }
            }

            $this->response($json);
            return;
        }

        $this->javascripts = am($this->javascripts, 'webtoolkit.aim', 'gallery');
        $this->pageTitle = __('Enter Contest',true);
        $this->set('isGallery', 1);
    } // upload

    public function manage ($status = 'P') {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $this->helpers = array_merge($this->helpers, array('Time'));

        $params = array(
            'conditions' => array('status' => $status),
            'recursive'  => -1,
            'order'      => array('order', 'id'),
            'limit'      => 10
        );
        $this->paginate = $params;

        $this->stylesheet  = am($this->stylesheet, 'sexylightbox/sexylightbox');
        $this->javascripts = am($this->javascripts, 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', 'jquery.easing.1.3', 'sexylightbox.v2.3.jquery.min');

        $this->pageTitle = __('Manage Gallery',true);
        $this->set('data', $this->paginate());
        $this->set('view', $status);
    } // manage

    public function update ($status) {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $form = $this->params['form'];

        if (isset($form['delete'])) {
            $data = $this->Gallery->find('all', array(
                'conditions' => array('id' => $form['ids']),
                'recursive'  => -1,
                'fields'     => array('filename')
            ));
            if ($this->Gallery->deleteAll(array('id' => $form['ids']))) {
                $path = IMAGES.'gallery'.DS;

                foreach ($data as $g) {
                    $file = $g['Gallery']['filename'];
                    @unlink($path.'s_'.$file);
                    @unlink($path.$file);
                }
                $this->Session->setFlash('<h4>'.__('Selected Gallery has been deleted.',true).'</h4>', 'default', array('class'=>'boxSuccess'));
            } else {
                $this->Session->setFlash('<h4>'.__('Fail deleting Gallery at this time, please try again.',true).'</h4>', 'default', array('class'=>'boxError'));
            }
        } else if (isset($form['approve'])) {
            if ($this->Gallery->updateAll(array('Gallery.status'=>'"A"'), array('id'=>$form['ids']))) {
                $this->Session->setFlash('<h4>'.__('Selected Gallery has been approved.',true).'</h4>', 'default', array('class'=>'boxSuccess'));
            } else {
                $this->Session->setFlash('<h4>'.__('Fail to approve Gallery at this time, please try again.',true).'</h4>', 'default', array('class'=>'boxError'));
            }
        } else if (isset($form['update'])) {
            foreach ($form as $k=>$v) {
                if (strpos($k, 'dr_')) {
                    $id = str_replace('odr_', '', $k);

                    $this->Gallery->id = $id;
                    $this->Gallery->saveField('order', $v);
                }
            }
            $this->Session->setFlash('<h4>'.__('Gallery has been updated.',true).'</h4>', 'default', array('class'=>'boxSuccess'));
        }

        $this->redirect('/galleries/manage/'.$status);
        //$this->render('manage');
    } // update

    public function index () {
        $data    = $main = $json = array();
        $gallery = $this->Gallery->find('all', array(
            'conditions' => array('status'=>'A'),
            'recursive'  => 0,
            'fields'     => array('id', 'title', 'description', 'author', 'filename'),
            'order'      => array('order', 'id DESC')
        ));

        foreach ($gallery as $i=>$a) {
            $data[$i] = $a['Gallery'];

            if ($a['Gallery']['filename']) {
                $data[$i]['filename'] = $a['Gallery']['filename'];
            } else {
                $data[$i]['filename'] = 'default.png';
            }

            if ($i > 5) {
                $json[] = $data[$i];
            } else {
                $main[] = $data[$i];
            }
        }

        /*for ($x=0; $x<30; $x++) {
            $json[] = array(
                'id'       => $x,
                'title'     => 'ATP Zeta Essential Pack '.$x,
                'filename' => '',
                'author'   => 'wayne cheah',
                'description' => 'Simplicity: Designed for efficiency and ease of use'
            );
        }*/

        $this->stylesheet  = am($this->stylesheet, 'sexylightbox/sexylightbox');
        $this->javascripts = am($this->javascripts, 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', 'jquery.easing.1.3', 'jquery.scrollTo-min', 'sexylightbox.v2.3.jquery.min');

        $this->pageTitle = __('Gallery',true);
        $this->set('data', $main);
        $this->set('count', $i);
        $this->set('isGallery', 1);
        $this->set('json', json_encode($json));
    } // index


    private function _sendMail ($data, $id) {
        $sitename = Configure::read('site.sitename');
        $sitename = __($sitename, true);
        $domain   = str_replace('www.', '', env('HTTP_HOST'));
        $delivery = (Configure::read('debug') > 1) ? 'mail' : 'mail';

        $this->Email->to       = 'hann@carelatex.com';
        $this->Email->replyTo  = $data['email'];
        $this->Email->from     = $sitename.' <noreply@'.$domain.'>';
        $this->Email->subject  = 'New gallery submitted by '.$data['author'];
        $this->Email->template = 'contest';
        $this->Email->sendAs   = 'html';
        $this->Email->delivery = $delivery;

        $secret = Configure::read('Security.salt');
        $code   = md5($id.$secret);
        $data   = array_merge($data, array(
            'domain' => 'http://'.env('HTTP_HOST').$this->base,
            'name'   => $data['title'],
            'url'    => Router::url('/galleries/manage/'.$id.'/'.$code, true),
            'code'   => $code,
            'date'   => date('d/m/Y H:i a')
        ));

        $this->set($data);
        $this->Email->send();
    } // _sendMail
} // GalleriesController

?>